
package fcl.platform;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.zip.GZIPOutputStream;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class Uploader extends IntentService {
	private NotificationManager notify_mgr;
	public Uploader() {
		super("Uploader");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		if(notify_mgr == null) {
			notify_mgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		}
		final String upload_file_name = Environment.getExternalStorageDirectory() + getString(R.string.data_folder) + getString(R.string.upload_file);
		final File upload_file = new File(upload_file_name);
		final File upload_gz_file = new File(upload_file_name + ".gz");
		
		
		if(upload_file.exists() && upload_file.length() > 0 && gzip_file(upload_file, upload_gz_file)) {
			
			//dshin
			Socket nsocket = null; //Network Socket
	        InputStream nis = null; //Network Input Stream
	        OutputStream nos = null; //Network Output Stream
	        FileInputStream myOutStream = null;
	        
			try { 
				
				Log.i("AsyncTask", "doInBackground: Creating socket");
                SocketAddress sockaddr = new InetSocketAddress("129.132.32.159", 8080);
                nsocket = new Socket();
                nsocket.connect(sockaddr, 10000);
                
                
				//FileInputStream myOutStream = null;
                //Socket socket = new Socket("129.132.32.159", 13938); //13938);
                //socket.setSoTimeout(5000);
                
               
                DataOutputStream out = new DataOutputStream(new BufferedOutputStream(nsocket.getOutputStream()));
                
                myOutStream = new FileInputStream(upload_gz_file);
                
                byte[] myByte;
                long len = upload_gz_file.length();
                myByte = new byte[(int) len];
                len = myOutStream.read(myByte);
                
                
                out.writeLong(myByte.length); 
                //Toast.makeText(getApplicationContext(), "Start uploading data file ;)", Toast.LENGTH_SHORT).show();
                
                out.flush();
                
                out.write(myByte);
                out.flush();
                
                //doNotify("Data file uploaded");
                //Toast.makeText(getApplicationContext(), "Data file uploaded ;)", Toast.LENGTH_SHORT).show();
				upload_file.renameTo(new File(Environment.getExternalStorageDirectory() + getString(R.string.data_folder) + System.currentTimeMillis() + ".dat"));
				upload_gz_file.delete();
                
                out.close();
                nsocket.close();
			
			
			/*
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
					HttpVersion.HTTP_1_1);
			try {
				doNotify("Start uploading data file");
				HttpPost post = new HttpPost("http://129.132.32.159/upload.php");
				MultipartEntity entity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);

				// For File parameters
				entity.addPart("file", new FileBody(upload_gz_file, System.currentTimeMillis() + ".dat.gz", "application/octet-stream", null));
				// add more parameters
				entity.addPart("client_id", new StringBody(get_client_id()));
				// entity.addPart("password", new StringBody("my pass"));
				
				post.setEntity(entity);
				if(client.execute(post).getStatusLine().getStatusCode() == 200) {
					doNotify("Data file uploaded");
					upload_file.renameTo(new File(Environment.getExternalStorageDirectory() + getString(R.string.data_folder) + System.currentTimeMillis() + ".dat"));
					upload_gz_file.delete();
				}
				else {
					doNotify("Data file uploading failed");
				}
			} catch (Exception e) {
				doNotify("Error happened while uploading file");
			} finally {
				client.getConnectionManager().shutdown();
			}*/
			} catch (Exception e) {
				//doNotify("Error happened while uploading file");
				//Toast.makeText(getApplicationContext(), "upload failed ;(", Toast.LENGTH_SHORT).show();
			} finally {
				//client.getConnectionManager().shutdown();
			}
		}
	}
	private String get_client_id() {
		SharedPreferences settings = getSharedPreferences(getString(R.string.pref_name), 0);
		String client_id = settings.getString(getString(R.string.client_id_key), null);
		
		if(client_id == null) {
			client_id = java.util.UUID.randomUUID().toString();
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(getString(R.string.client_id_key), client_id);
			editor.commit();
		}
		return client_id;
	}
	
	private boolean gzip_file(File file, File gz_file) {
		FileInputStream fileInputStream = null;
		GZIPOutputStream gzipOutputStream= null;
		if(gz_file.exists() && gz_file.length() > 0) {
			return true;
		}
		try {
			fileInputStream = new FileInputStream(file);
			gzipOutputStream = new GZIPOutputStream(new FileOutputStream(gz_file));
			byte[] buf = new byte[1024];  //size can be 
			int len;
			while ((len = fileInputStream.read(buf)) > 0) {
				gzipOutputStream.write(buf, 0, len);
			}
			gzipOutputStream.finish();
			gzipOutputStream.flush();
			gzipOutputStream.close();
			fileInputStream.close();
			return true;
		} catch(Exception e) {
			if(fileInputStream != null) {
				try {fileInputStream.close();} catch (IOException e1) {}
			}
			if(gzipOutputStream != null) {
				try {gzipOutputStream.close();} catch (IOException e1) {}
			}
			gz_file.delete();
			return false;
		}
	}
	void doNotify(String content) {
/*		Notification notification = new Notification(android.R.drawable.arrow_up_float,
				content, System.currentTimeMillis());
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, R.class), 0);
		notification.setLatestEventInfo(this,
				"data uploader", content, contentIntent);
		notification.flags = Notification.FLAG_AUTO_CANCEL ;

		// Send the notification.
		// startForeground(R.string.data_logger_started, notification);
		notify_mgr.notify(R.string.upload_service, notification);
*/	}
}
